<template>
  <div class="app-container" style="display: flex;">
    <div style="width: 60%;padding-right: 10px">
      <h3>验收上报</h3>
      <el-form ref="dataForm" :rules="rules" :model="goods">
        <el-form-item label="项目" prop="status">
          <el-select
            v-model="goods.shopName"
            :disabled="this.$route.query.id || this.$route.query.shopId"
            clearable
            style="width: 200px"
            class="filter-item"
            placeholder="请选择项目"
            @change="selectProductType"
          >
            <el-option v-for="(item,index) in shopList" :key="index" :label="item.shopName" :value="{ value: item.id, label: item.shopName}"/>
          </el-select>
        </el-form-item>
        <el-form-item label="验收说明" prop="description">
          <el-input v-model="goods.description" type="textarea" />
        </el-form-item>
        <el-form-item label="验收人" prop="yanshouName">
          <el-input v-model="goods.yanshouName" />
        </el-form-item>
        <el-form-item label="验收人电话" prop="yanshouPhone">
          <el-input v-model="goods.yanshouPhone" />
        </el-form-item>
        <el-form-item label="验收时间">
          <el-date-picker
            v-model="goods.gmtDay"
            :picker-options="pickerOptions"
            type="date"
            placeholder="选择日期"
            align="right"/>
        </el-form-item>
        <!--        <el-form-item label="图片">
          <el-upload
            :action="uploadPath"
            :headers="headers"
            :limit="5"
            :file-list="imgsFileList"
            :on-exceed="uploadOverrun"
            :on-success="handleimgsUrl"
            :on-remove="handleRemove"
            multiple
            accept=".jpg, .jpeg, .png, .gif"
            list-type="picture-card"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>-->

        <el-form-item label="文件">
          <el-upload
            :action="uploadPath"
            :headers="headers"
            :limit="5"
            :file-list="fileList"
            :on-success="handleFileUrl"
            :on-remove="handleFileRemove"
            multiple
            accept=".jpg, .jpeg, .png, .gif, .doc, .docx, .xls, .xlsx, .zip, .rar"
            list-type="text"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>

      </el-form>
      <!--      <el-card class="box-card">
        <h3>工程信息</h3>
        <el-table :data="biaozhunList">
          <el-table-column property="gongchengName" label="工程名称" />
          <el-table-column property="gongchengCode" label="工程编号" />
          <el-table-column property="gongcheng_count" label="工程总量" />
          <el-table-column property="bunit" label="单位" />
          <el-table-column label="今日完成量" property="today_count">
            <template slot-scope="scope">
              <el-input v-model="scope.row.today_count" controls-position="right" style="width: 100px" class="inputClass"/>
            </template>
          </el-table-column>
        </el-table>
      </el-card>-->
      <div class="op-container">
        <el-button @click="handleCancel">取消</el-button>
        <el-button v-if="!goods.id" type="primary" @click="handleCreate">保存</el-button>
        <el-button v-if="goods.id" type="primary" @click="handleEdit">更新</el-button>
      </div>
    </div>
  </div>
</template>

<style>
.el-card {
  margin-bottom: 10px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>

<script>
import { detailGoods, editGoods, createGoods, freezeOrActivtion } from '@/api/yanshou'
import { uploadPath } from '@/api/storage'
import Editor from '@tinymce/tinymce-vue'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import { selectShop } from '@/api/frontutil'
// import { listByBiaozhun } from '@/api/shopBiaozhun'

export default {
  name: 'GoodsUpsert',
  components: { Editor },
  data() {
    return {
      uploadPath,
      shopList: [],
      isShow: false,
      biaozhunList: [],
      gongchengLog: {},
      gongchengBiaozhunList: [],
      freightList: [],
      imgsFileList: [],
      fileList: [],
      categoryList: [],
      categoryIds: [],
      shigong: {},
      goods: {
        imgList: [],
        fileList: [],
        priceRaw: 0,
        shopId: this.$route.query.shopId,
        shopName: this.$route.query.shopName
      },
      attributeVisiable: false,
      attributeForm: { attribute: '', value: '' },
      attributes: [],
      skuStatus: '',
      rules: {

      }

    }
  },
  computed: {

    headers() {
      return {
        accessToken: getToken()
      }
    }
  },
  created() {
    this.init()
    this.listShop()
  },
  methods: {
    init: function() {
      const goodsId = this.$route.query.id
      if (goodsId) {
        detailGoods(goodsId).then(response => {
          this.goods = Object.assign({}, response.data.data)
          // this.biaozhunList = this.goods.biaozhunList
          this.imgsFileList = []
          if (this.goods.imgList) {
            for (var i = 0; i < this.goods.imgList.length; i++) {
              this.imgsFileList.push({
                url: this.goods.imgList[i]
              })
            }
          } else {
            this.goods.imgList = []
          }
          if (this.goods.fileList) {
            for (var j = 0; j < this.goods.fileList.length; j++) {
              this.fileList.push({
                name: this.goods.fileList[j].name,
                url: this.getPreviwImg(this.goods.fileList[j].name)
              })
            }
          } else {
            this.goods.fileList = []
          }
        })
      }
    },
    listShop() {
      selectShop()
        .then(response => {
          this.shopList = response.data.data
        })
        .catch(() => {
        })
    },
    selectProductType(data) {
      const { value, label } = data
      this.goods.shopName = label
      this.goods.shopId = value
    },

    handleCancel: function() {
      var url = '/yanshou/yanshou'
      if (this.$route.query.shopId) {
        url = url + '?shopId=' + this.$route.query.shopId + '&shopName=' + this.$route.query.shopName
      }
      this.$router.push({ path: url })
    },
    handleShenheBohui: function() {
      freezeOrActivtion(this.gongchengLog.id, 1).then(response => {
        this.gongchengLog.status = 1
        this.$notify.success({
          title: '成功',
          message: '已驳回'
        })
      }).catch(() => { })
    },
    handleShenheTongguo: function() {
      freezeOrActivtion(this.gongchengLog.id, 2).then(response => {
        this.gongchengLog.status = 2
        this.$notify.success({
          title: '成功',
          message: '审核通过'
        })
      }).catch(() => { })
    },
    handleCreate: function() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const finalGoods = {
            ...this.goods,
            biaozhunList: this.biaozhunList
          }
          createGoods(finalGoods)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '添加成功'
              })
              var url = '/yanshou/yanshou'
              if (this.$route.query.shopId) {
                url = url + '?shopId=' + this.$route.query.shopId + '&shopName=' + this.$route.query.shopName
              }
              this.$router.push({ path: url })
            })
            .catch(response => {
              MessageBox.alert('错误：' + response.data.errmsg, '警告', {
                confirmButtonText: '确定',
                type: 'error'
              })
            })
        } else {
          this.$notify.error({
            title: '失败',
            message: '请完善以上表单'
          })
        }
      })
    },
    handleEdit: function() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const finalGoods = {
            ...this.goods
            // biaozhunList: this.biaozhunList
          }
          editGoods(finalGoods)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '编辑成功'
              })
              var url = '/yanshou/yanshou'
              if (this.$route.query.shopId) {
                url = url + '?shopId=' + this.$route.query.shopId + '&shopName=' + this.$route.query.shopName
              }
              this.$router.push({ path: url })
            })
            .catch(response => {
              MessageBox.alert('错误：' + response.data.errmsg, '警告', {
                confirmButtonText: '确定',
                type: 'error'
              })
            })
        } else {
          this.$notify.error({
            title: '失败',
            message: '请完善表单'
          })
        }
      })
    },
    uploadOverrun: function() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传5张图片!'
      })
    },
    handleimgsUrl(response, file, fileList) {
      if (response.errno === 200) {
        this.goods.imgList.push(response.url)
      }
    },
    handleFileUrl(response, file, fileList) {
      if (response.errno === 200) {
        this.goods.fileList.push(
          {
            name: file.name,
            url: response.url

          }
        )
      }
    },
    handleRemove: function(file, fileList) {
      for (var i = 0; i < this.goods.imgList.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url

        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.url
        }
        if (this.goods.imgList[i] === url) {
          this.goods.imgList.splice(i, 1)
        }
      }
    },
    handleFileRemove: function(file, fileList) {
      for (var i = 0; i < this.goods.fileList.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url

        if (this.goods.fileList[i].name === file.name) {
          this.goods.fileList.splice(i, 1)
        }
      }
    },
    getImgUrl(image) {
      return require(`@/assets/file/${image}`)
    },
    getPreviwImg(filename) {
      filename = filename
        .substring(filename.lastIndexOf('.'))
        .toLowerCase()
        .split('.')[1]
      const imageObject = {
        png: 'png.png',
        jpg: 'png.png',
        jpeg: 'png.png',
        gif: 'png.png',
        doc: 'doc.png',
        docx: 'doc.png',
        xls: 'xls.png',
        xlsx: 'xls.png',
        pdf: 'pdf.png',
        zip: 'zip.png',
        '7z': 'zip.png',
        rar: 'zip.png',
        txt: 'file.png'
      }
      return this.getImgUrl(imageObject[filename])
    }

  }
}
</script>
